<template>
   <div class="flex justify-center items-center min-h-screen login" v-loading="loadingVisible" element-loading-background="rgba(122, 122, 122, 0.8)">
      <el-card>
         <p class="flex justify-center text-2xl font-bold mb-4">{{ $store.state.projectTitile }}</p>
         <el-form :model="formData" :rules="formRules" ref="formRef">
            <el-form-item prop="username">
               <el-input :prefix-icon="User" v-model="formData.username" autocomplete="off" placeholder="请输入用户名" clearable/>
            </el-form-item>
            <el-form-item prop="password">
               <el-input type="password" show-password :prefix-icon="Lock" v-model="formData.password" autocomplete="off" placeholder="请输入密码" clearable/>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" @click="submitForm">登录</el-button>
            </el-form-item>
         </el-form>
      </el-card>
   </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { loginReq } from "@/api/login.js"
import { useRouter } from 'vue-router'
import { success } from '@/utils/messageUtils.js';
import { setToken,removeToken } from '@/utils/token.js'
import { User,Lock } from '@element-plus/icons-vue'

const formData = reactive({
   username: '',
   password: '',
});

const formRules = {
   username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
   password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const router = useRouter();
const loadingVisible = ref(false)

const formRef = ref()
const submitForm = () => {
   formRef.value.validate((isValidate, fields) => {
      if (isValidate) {
         loadingVisible.value = true;
         console.log("formData", formData)
         loginReq(formData).then(res => {
            if (res.code == 200) {
               // 移除之前的token
               removeToken()
               // 存储新的token
               setToken(res.data)
               router.push("/home");
               success("登录成功！")
            }
         }).finally(() => { loadingVisible.value = false; })
      }
   });
};
</script>

<style>
.login {
   background-image: url("../images/login-background.jpg");
   background-size: cover;
}
</style>